package cn.layfolk.uaa.server;

import cn.layfolk.uaa.domain.TPermission;
import cn.layfolk.daimao.vo.TUser;
import cn.layfolk.uaa.mapper.TUserMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义UserDetailsService  可以支持密码模式
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {
    @Autowired
    private TUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //登录账号
        System.out.println("username=" + username);
        //根据账号去数据库查询...
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        TUser user = userMapper.selectOne(wrapper);
        if (user == null) {
            return null;
        }
        //查询用户权限

        List<TPermission> tPermissions = userMapper.findPermissionsByUserId(user.getClientDetailsId());
        List<String> permissions = new ArrayList<>();
        tPermissions.forEach( p -> permissions.add(p.getCode()));
        String[] perarray = new String[permissions.size()];
        permissions.toArray(perarray);

        //创建userDetails
        //这里将user转为json，将整体user存入userDetails   1.扩展userDetails存入更多属性 2.扩展username
        String principal = JSON.toJSONString(user);

        UserDetails userDetails =
                // 这里如果传principal 就把所有数据传过去了，还不破坏userDetails结构
                User.withUsername(user.getUsername()).password(user.getPassword()).authorities(perarray).build();
        return userDetails;
    }
}
